package com.lwlean.test.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Created by lean on 2017/2/13.
 */
public class RestTemplateUtil {

    private static final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);

    public static String setRestTemplate(String uri, String parameters, String method) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setAcceptCharset(Arrays.asList(StandardCharsets.UTF_8));
        HttpEntity<String> entity = null;
        HttpMethod httpMethod = null;
        log.info("use url:{}", uri);
        log.info("use method:{}", method);
        log.info("use parameters:{}", parameters);
        if (StringUtils.equals("post", method)) {
            httpMethod = HttpMethod.POST;
            entity = new HttpEntity<String>(parameters, headers);
        } else if (StringUtils.equals("get", method)) {
            httpMethod = HttpMethod.GET;
            entity = new HttpEntity<String>(headers);
        } else if (StringUtils.equals("delete", method)) {
            httpMethod = HttpMethod.DELETE;
            entity = new HttpEntity<String>(parameters, headers);
        } else if (StringUtils.equals("put", method)) {
            httpMethod = HttpMethod.PUT;
            entity = new HttpEntity<String>(parameters, headers);
        }
        try {
            ResponseEntity<String> result = restTemplate.exchange(uri, httpMethod, entity, String.class);
            final HttpStatus statusCode = result.getStatusCode();
            final String body = result.getBody();
            log.info("send result:{}", statusCode);
            return body;
        } catch (Exception e) {
            log.error("catch exception:", e);
            return null;
        }
    }
}
